const { defineConfig } = require('@vue/cli-service');
const fs = require('fs');
const { NacosNamingClient } = require('nacos');
// 创建 NacosNamingClient 实例
const namingClient = new NacosNamingClient({
  logger: console,
  serverList: '47.116.164.60:10050', // Nacos 服务地址
  namespace: 'zgyd',
  username: 'nacos',
  password: 'nacos'
});

// 异步函数用于获取指定名称的服务列表
async function fetchServiceList(serviceName, groupName) {
  await namingClient.ready();

  // 获取指定名称的服务列表
  try {
    let serviceList = await namingClient.getAllInstances(serviceName, groupName);
    console.log('serviceList = ',serviceList);
    if (serviceList && serviceList.length > 0) {
      let { ip, port } = serviceList[0];
      return `http://${ip}:${port}`;
    }
    throw new Error('没有找到gateway服务');
  } catch (error) {
    console.error('无法获取服务列表:', error);
    return null;
  }

}

module.exports = defineConfig(async () => {
  let gatewayService = await fetchServiceList('gateway-server', 'meng');
  console.log('gatewayService = ', gatewayService);

  // 定时重新获取网关服务地址
  setInterval(async () => {
    try {
      gatewayService = await fetchServiceList('gateway-server', 'meng');
      console.log('gatewayService 更改为：', gatewayService);
    } catch (error) {
      console.error('更改gatewayService错误:', error);
    }
  }, 60000); // 每隔一分钟重新获取一次

  return {
    transpileDependencies: true,
    devServer: {
      https: {
        key: fs.readFileSync('src\\utils\\key\\key.pem'),
        cert: fs.readFileSync('src\\utils\\key\\cert.pem'),
      },
      port: 8080,
      allowedHosts: [
        '.ngrok-free.app', // 允许访问的域名地址， 
      ],
      proxy: {
        "^/api": {
          target: gatewayService, // 将从 Nacos 获取的网关 IP 地址设为代理目标服务器地址
          changeOrigin: true,
          pathRewrite: {
            '^/api': '/'
          }
        },

        "/getAddress": {
          //1：匹配代理规则
          target: "https://restapi.amap.com/v3/config", // 高德地图查询城市
          changeOrigin: true, // 3：允许跨域请求
          pathRewrite: {
            "^/getAddress": "/", // 4：把路径的/getAddress 换成 /
          },
        },
      },
      open: { app: { name: 'chrome' } }
    },
  };
});
